<?php

namespace App\Http\Controllers;

use App\Models\Comments;
use App\Models\Praises;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 点赞相关
 * Class FollowController
 * @package App\Http\Controllers
 */
class PraiseController extends Controller{

    /**
     * 用户点赞集合
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        try {
            $id = (int)$request->get('id');
            if(empty($id)){
                return $this->returnJson(1,'参数错误');
            }
            $lists = Praises::select('id','user_id','comment_id')->where('video_id',$id)->get();
            return $this->returnJson(0, '', $lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

    /**
     * 点赞评论
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request){
        try {
            $data = $request->all();
            if(empty($data['video_id']) || empty($data['comment_id'])){
                return $this->returnJson(1,'参数错误');
            }
            $data['user_id'] = auth()->guard('api')->id();
            $data['created_at'] = Carbon::now();
//            //更新评论总点赞
            $praise = Praises::where('video_id',$data['video_id'])
                ->where('comment_id',$data['comment_id'])
                ->where('user_id',$data['user_id'])
                ->orderBy('created_at','DESC')
                ->first();
            if($praise && (time()-$praise['created_at']->timestamp < 5)){
                return $this->returnJson(1,'你的操作太频繁');
            }
            DB::transaction(function () use($data){
                //更新点赞记录
                Praises::create($data);
                $comment = Comments::find($data['comment_id']);
                //更新评论总点赞
                $comment->increment('praise');
//                if($praise){
//                    //删除点赞记录
//                    $praise->delete();
//                    //删减评论总点赞
//                    $comment->decrement('praise');
//                }else{
//
//                }
            });
            return $this->returnJson(0);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

}
